package com.easy.common.util.file;
import java.io.*;
import java.sql.Connection;
import java.util.*;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.log4j.Logger;
//import com.easy.data.MYRequestDbConn;
import com.easy.common.constant.Const;
import com.easy.common.constant.SysProps;
import com.easy.common.util.Utility;

public class FileUploadForm {

	private static Logger log = Logger.getLogger("com.easy.util.file.MYFileUploadForm");
	private HashMap paramMap;
	private List fileList;
	private HashMap fileMap;
	private HttpServletRequest request;

	public FileUploadForm()
	{
		paramMap = new HashMap();
		fileList = new ArrayList();
		fileMap = new HashMap();
		request = null;
	}

	public Map getParamMap()
	{
		return paramMap;
	}

	public void parseUploadRequest(HttpServletRequest request)
		throws Exception
	{
		this.request = request;
		File tmpFile = new File(SysProps.getUploadCatchPath());
		if (!tmpFile.exists())
			tmpFile.mkdirs();
		parseUploadRequest(request, SysProps.getInt("maxUploadFileSize"), 10240, SysProps.getString("fileUploadTempDir"), Const.DEFAULT_CODE);
	}

	public void parseUploadRequest(HttpServletRequest request, int maxSize, int buffSize, String tempPath, String charSet)
		throws Exception
	{
		DiskFileUpload fu = new DiskFileUpload();
		fu.setHeaderEncoding(charSet);
		fu.setSizeMax(maxSize * 0x100000);
		fu.setSizeThreshold(buffSize);
		if (!Utility.isNullorEmpty(tempPath))
			fu.setRepositoryPath(tempPath);
		List fieldList = fu.parseRequest(request);
		for (Iterator iter = fieldList.iterator(); iter.hasNext();)
		{
			FileItem item = (FileItem)iter.next();
			if (!item.isFormField())
			{
				fileList.add(item);
				fileMap.put(item.getFieldName(), item);
			} else
			if (charSet != null)
				paramMap.put(item.getFieldName(), item.getString(charSet));
			else
				paramMap.put(item.getFieldName(), item.getString());
		}

	}

	public String getParameter(String paramName)
	{
		return (String)paramMap.get(paramName);
	}

	public Iterator iterateFileFields()
	{
		return fileMap.keySet().iterator();
	}

	public Iterator iterateParamFiels()
	{
		return paramMap.keySet().iterator();
	}

	public FileItem getFileItem(String fieldName)
	{
		return (FileItem)fileMap.get(fieldName);
	}

	public InputStream getInputStream()
		throws IOException
	{
		if (fileList == null)
		{
			return null;
		} else
		{
			FileItem fileItem = (FileItem)fileList.get(0);
			return fileItem.getInputStream();
		}
	}

	public InputStream getInputStream(String fieldName)
		throws IOException
	{
		FileItem item = getFileItem(fieldName);
		if (item != null)
			return item.getInputStream();
		else
			return null;
	}

	public String getFileExt(FileItem fileItem)
		throws IOException
	{
		return FileUtility.getFileExtName(fileItem.getName());
	}

	public String getFileExt(String fieldName)
		throws IOException
	{
		return getFileExt(getFileItem(fieldName));
	}

	public String getFileExt()
		throws IOException
	{
		if (fileList == null)
		{
			return null;
		} else
		{
			FileItem fileItem = (FileItem)fileList.get(0);
			return getFileExt(fileItem);
		}
	}

	public String getFileNameNoExt()
		throws IOException
	{
		if (fileList == null)
		{
			return null;
		} else
		{
			String fileName = getFileName();
			return FileUtility.getFileNameNoExt(fileName);
		}
	}

	public String getFileName(FileItem fileItem)
		throws IOException
	{
		return FileUtility.getFileName(fileItem.getName());
	}

	public String getFileName(String fieldName)
		throws IOException
	{
		return getFileName(getFileItem(fieldName));
	}

	public long getFileSize(String fieldName)
		throws IOException
	{
		FileItem fileItem = getFileItem(fieldName);
		if (fileItem == null)
			return 0L;
		else
			return fileItem.getSize();
	}

	public String getFileName()
		throws IOException
	{
		if (fileList == null)
		{
			return null;
		} else
		{
			FileItem fileItem = (FileItem)fileList.get(0);
			return getFileName(fileItem);
		}
	}

	private void saveFile(FileItem fileItem, String savePath)
		throws IOException
	{
		File outFile;
		InputStream in;
		OutputStream out;
		if (fileItem == null)
			return;
		if (savePath == null)
			return;
		outFile = new File(savePath);
		File outPath = outFile.getParentFile();
		if (!outPath.exists())
			outPath.mkdirs();
		if (!outFile.exists())
			outFile.createNewFile();
		in = null;
		out = null;
		try
		{
			in = new BufferedInputStream(fileItem.getInputStream());
			out = new BufferedOutputStream(new FileOutputStream(outFile));
			byte buff[] = new byte[0x100000];
			for (int length = 0; (length = in.read(buff)) > 0;)
			{
				out.write(buff, 0, length);
				out.flush();
			}

		}
		catch (IOException ex)
		{
			throw ex;
		}
		finally{
			try
			{
				if (in != null)
					in.close();
				if (out != null)
					out.close();
			}
			catch (IOException ex1) {
				throw ex1;
			}
		}
		String tmpStr = null;
		int tmpIndex = savePath.lastIndexOf("\\");
		if (tmpIndex >= 4)
		{
			tmpStr = savePath.substring(tmpIndex - 4);
			tmpStr = tmpStr.replace("\\", "_");
		}
		if (tmpStr != null && Pattern.matches("^\\d{4}_[0-9a-z]{32}_.*$", tmpStr))
		{
			tmpIndex = tmpStr.indexOf("_", 5);
			String fileId = tmpStr.substring(0, tmpIndex);
			Connection dbConn = null;
			try
			{
//				MYRequestDbConn requestDbConn = (MYRequestDbConn)request.getAttribute("requestDbConnMgr");
//				dbConn = requestDbConn.getSysDbConn();
//				MYORM orm = new MYORM();
//				Map valueMap = new HashMap();
//				valueMap.put("fileId", fileId);
//				valueMap.put("filePath", savePath);
//				valueMap.put("createTime", MYUtility.getCurDateTimeStr());
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
				throw new IOException(ex);
			}
		}
		return;
	}

	public void saveFile(String fieldName, String savePath)
		throws IOException
	{
		saveFile(getFileItem(fieldName), savePath);
	}

	public void saveFile(String savePath)
		throws IOException
	{
		if (fileList == null)
		{
			return;
		} else
		{
			FileItem fileItem = (FileItem)fileList.get(0);
			saveFile(fileItem, savePath);
			return;
		}
	}

	public String saveFileAll(String savePath)
		throws IOException
	{
		String filePrefix = null;
		filePrefix = Utility.getRandomName();
		return saveFileAll(savePath, filePrefix);
	}

	public String saveFileAll(String savePath, String filePrefix)
		throws IOException
	{
		if (fileList == null)
			return null;
		if (filePrefix == null)
			filePrefix = "";
		for (int i = 0; i < fileList.size(); i++)
		{
			FileItem fileItem = (FileItem)fileList.get(i);
			String fileExtName = getFileName(fileItem);
			if (!Utility.isNullorEmpty(fileExtName))
			{
				String filePath = (new StringBuilder(String.valueOf(savePath))).append("\\").toString();
				if (!Utility.isNullorEmpty(filePrefix))
					filePath = (new StringBuilder(String.valueOf(filePath))).append(filePrefix).append("\\").toString();
				filePath = (new StringBuilder(String.valueOf(filePath))).append(fileExtName).toString();
				saveFile(fileItem, filePath);
			}
		}

		return filePrefix;
	}

	public String getExists(String savePath)
		throws IOException
	{
		if (fileList == null)
			return null;
		for (int i = 0; i < fileList.size(); i++)
		{
			FileItem fileItem = (FileItem)fileList.get(i);
			String fileExtName = getFileName(fileItem);
			if (!Utility.isNullorEmpty(fileExtName))
			{
				String filePath = (new StringBuilder(String.valueOf(savePath))).append("\\").append(fileExtName).toString();
				if ((new File(filePath)).exists())
					return fileExtName;
			}
		}

		return null;
	}


}
